package com.xuya.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import com.xuya.entity.Product;
import com.xuya.util.DBHelp;
import com.xuya.util.RowMapper;

public class ProductDao {
	private DBHelp<Product> db = new DBHelp<Product>();
	public Product findProduct(int id){
		String sql = "select p_id,p_name,p_price from t_prod where p_id = ?";
		return db.executeForObject(sql,new ProductRowMapper(),id);
	}
	public Product findProductByname(String name){
		String sql = "select p_id,p_name,p_price from t_prod where p_name = ?";
		return db.executeForObject(sql,new ProductRowMapper(),name);
	}
	public List<Product> findAllProduct(){
		String sql = "select p_id,p_name,p_price from t_prod ";
		return db.executeForList(sql,new ProductRowMapper());
	}
	public boolean delProduct(int id){
		String sql = "DELETE FROM t_prod WHERE p_id = ?";
		return db.executeSQL(sql,id);
		
	}
	public boolean saveProduct(Product pro){
		String sql = "INSERT INTO t_prod(p_name,p_price) VALUES (?,?)";
		return db.executeSQL(sql, pro.getName(),pro.getPrice());
		
	}
	public boolean editProduct(Product p){
		String sql = "update t_prod set p_name = ?,p_price = ? where p_id = ?";
		return db.executeSQL(sql, p.getName(),p.getPrice(),p.getId());
		
	}
	
	private class ProductRowMapper implements RowMapper<Product>{
		public Product mapperRow(ResultSet res) throws SQLException {
			Product p = new Product();
			p.setId(res.getInt("p_id"));
			p.setName(res.getString("p_name"));
			p.setPrice(res.getFloat("p_price"));
			return p;
		}
		
		
	}
	
}

